<!--表格内的上传-->
<template>
  <dir v-loading="loading" class="tableUpload-box">
    <div v-if="imagesurlstr">
      <div class="view">
        <div v-if="isPdf === 'pdf'" class="el-image">
          <el-image :src="require('@assets/img/pdf.jpg')" @click="previewpdf" />
        </div>
        <el-image
          v-else
          :fit="fitType"
          :preview-src-list="[imagesurlstr]"
          :src="require('@assets/img/jpg.png')"
        />
        <span>{{ fileName }}</span>
      </div>
    </div>
    <div v-else style="display:flex;">
      <el-upload
        class="dialog-upload"
        action="string"
        :show-file-list="false"
        :accept="imageLimit"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeUpload"
        :http-request="toRequest"
        fit="scale-down"
      >
        <div class="view" style="width:100px;">
          <img src="@assets/img/upload.png" />
          <span>上传附件</span>
        </div>
      </el-upload>
      <div
        class="view"
        style="width:34px; margin-left:10px;"
        @click="qrcodeBtn"
      >
        <img src="@assets/img/erCode.png" />
      </div>
    </div>
    <el-dialog
      title="二维码"
      custom-class="dialog-er"
      :before-close="backClick"
      :visible.sync="erCOdeDialogVisible"
      width="400px"
    >
      <img :src="qrcodeImg" alt />
      <p>请用手机扫描二维码</p>
    </el-dialog>
  </dir>
</template>

<script>
import QRCode from 'qrcode';
import { getFileUploadCode, getFileUrlByCode } from '@const/fileLibraryApi.js';
import { hasIn } from 'lodash';
import { fileUpload } from '@const/api.js';
import { fitType } from '@const/common.js';
// import { without } from 'lodash';
// import { setImmediate } from 'timers';
// 文件上传限制 ------- 图片类型
// const imageLimit = '.pdf,.png,.jpg'
export default {
  name: 'TableUpload',
  props: {
    // 接收默认url
    imgsrc: {
      type: String,
      default: () => ''
    },
    imgname: {
      type: String,
      default: () => ''
    },
    // 接收多张
    imgsrcarr: {
      type: Array,
      default: () => []
    },
    // 跟单独调用没有关系，该值为了配合表单组件使用
    keystr: {
      type: Number,
      default: () => 0
    },
    // 类型
    uptype: {
      type: String,
      default: () => ''
    },
    imageLimit: {
      type: String,
      default: () => '.pdf,.png,.jpg'
    },
    imageSize: {
      type: Number,
      default: () => 3
    }
  },
  data() {
    return {
      myInterval: null,
      erCOdeDialogVisible: false,
      qrcodeImg: '',
      backVisible: false,
      qrcodeLoading: false,
      code: '',
      loading: false,
      isPdf: '',
      fileName: this.imgname || '',
      // 类型
      type: this.uptype || '',
      // 该值为了配合表单组件使用
      key: this.keystr || 0,
      // 图片填充行为
      fitType,
      // 上传的地址
      uploadUrl: fileUpload,
      // 多张上传的图片地址
      imagesurlarr: this.imgsrcarr || [],
      // 单张
      imagesurlstr: this.imgsrc || ''
    };
  },

  watch: {
    imgname: {
      immediate: true,
      handler(val) {
        this.fileName = val;
      }
    },
    imgsrc: {
      immediate: true,
      handler(val) {
        this.imagesurlstr = val;
        // this.fileName = val.substring(val.lastIndexOf('/') + 1);
        this.isPdf = val.replace(/.+\./, '').toLowerCase();
      }
    },
    imageLimit: {
      immediate: true,
      handler(val) {
        // eslint-disable-next-line vue/no-mutating-props
        this.imageLimit = val;
      }
    },
    imageSize: {
      immediate: true,
      handler(val) {
        // eslint-disable-next-line vue/no-mutating-props
        this.imageSize = Number(val);
      }
    }
  },
  methods: {
    qrcodeBtn() {
      this.loading = true;
      const originUrl = window.location.origin.includes('.com')
        ? window.location.origin
        : 'https://md.heng-tai.com.cn';
      this.$axios({
        url: getFileUploadCode,
        method: 'post'
      }).then(res => {
        const code = hasIn(res, ['data', 'payload']) ? res.data.payload : '';
        if (!code) {
          this.$message({
            type: 'warning',
            message: '获取状态码失败，请联系管理员！'
          });
          return;
        }
        this.code = code;
        QRCode.toDataURL(
          `${originUrl}/guoke-deepexi-utils-server-h5/#/file?token=${this.$store.state.token}&code=${code}`
        )
          .then(url => {
            this.qrcodeImg = url;
            this.erCOdeDialogVisible = true;
            this.setTimer();
          })
          .catch(() => {
            this.$message({
              type: 'error',
              message: '生成二维码失败，建议使用本地上传！'
            });
            this.loading = false;
          });
      });
    },
    // 轮询
    setTimer() {
      this.myInterval = window.setInterval(() => {
        setTimeout(() => {
          this.polling(); // 调用接口的方法
        }, 1);
      }, 3000);
    },
    // 查询扫码上传接口
    polling() {
      this.$axios({
        url: getFileUrlByCode,
        method: 'post',
        data: { code: this.code }
      })
        .then(res => {
          const imgUrl = hasIn(res, ['data', 'payload'])
            ? res.data.payload
            : '';
          if (!imgUrl) {
            // this.cancleConfirm();
            return;
          }
          this.imagesurlstr = imgUrl;
          const name = imgUrl.substring(imgUrl.lastIndexOf('/') + 1);
          this.$emit('ReturnImgUrl', this.imagesurlstr, this.key, name);
          this.isPdf = this.fileName.replace(/.+\./, '').toLowerCase();
          this.erCOdeDialogVisible = false;
          this.loading = false;
          clearInterval(this.myInterval);
          this.$message({
            type: 'success',
            message: '上传成功',
            duration: 2000
          });
        })
        .catch(() => {
          this.erCOdeDialogVisible = false;
          this.loading = false;
          clearInterval(this.myInterval);
          this.$message({
            type: 'warning',
            message: '获取上传图片失败，建议使用本地上传！'
          });
        });
    },
    // 取消提示
    // cancleConfirm() {
    //   this.$confirm('还未检测到通过二维码上传的文件，是否取消二维码上传?', '提示', {
    //     confirmButtonText: '是',
    //     cancelButtonText: '否',
    //     type: 'warning'
    //   })
    //     .then(() => {
    //       this.erCOdeDialogVisible = false;
    //       this.loading = false;
    //     })
    //     .catch(() => {});
    // },
    backClick() {
      this.erCOdeDialogVisible = false;
      this.loading = false;
      clearInterval(this.myInterval);

      // this.$axios({
      //   url: getFileUrlByCode,
      //   method: 'post',
      //   data: { code: this.code }
      // })
      //   .then(res => {
      //     let imgUrl = hasIn(res, ['data', 'payload']) ? res.data.payload : '';
      //     if (!imgUrl) {
      //       this.cancleConfirm();
      //       return;
      //     }
      //     this.imagesurlstr = imgUrl;
      //     this.fileName = imgUrl.substring(imgUrl.lastIndexOf('/') + 1);
      //     this.$emit('ReturnImgUrl', this.imagesurlstr, this.key, this.fileName);
      //     this.isPdf = this.fileName.replace(/.+\./, '').toLowerCase();
      //     this.erCOdeDialogVisible = false;
      //     this.loading = false;
      //     this.$message({ type: 'success', message: '上传成功', duration: 2000 });
      //   })
      //   .catch(err => {
      //     console.log(err);
      //     this.erCOdeDialogVisible = false;
      //     this.loading = false;
      //     this.$message({
      //       type: 'warning',
      //       message: '获取上传图片失败，建议使用本地上传！'
      //     });
      //   });
    },
    // pdf预览
    previewpdf() {
      this.$pdfViewer({ url: this.imagesurlstr, title: 'PDF预览' });
    },
    // 上传图片成功 本地图片地址
    handleAvatarSuccess(res, file) {
      this.localImgurl = URL.createObjectURL(file.raw);
      this.$emit('uploadPIC', 'ASDAS');
    },
    chuan() {
      this.$emit('zichuan', 'asdasd');
    },
    // 点击上传
    beforeUpload() {
      // this.uploadActon(file)
    },
    // eslint-disable-next-line consistent-return
    toRequest(dataA) {
      const isJPG = this.imageLimit.includes(
        dataA.file.name.replace(/.+\./, '').toLowerCase()
      );
      if (!isJPG) {
        this.$message.error(`上传失败，支持上传${this.imageLimit}格式文件!`);
        return false;
      }
      const isLt2M = dataA.file.size / 1024 / 1024 < this.imageSize;
      if (!isLt2M) {
        this.$message.error(`文件过大，请上传小于${this.imageSize}MB的文件!`);
        return false;
      }
      // // 发起请求
      const fd = new FormData();
      fd.append('file', dataA.file);
      this.loading = true;
      this.$axios({
        method: 'post',
        url: this.uploadUrl,
        headers: { 'Content-Type': 'multipart/form-data' },
        data: fd
      })
        .then(res => {
          // 赋值上传后的地址给文档
          // if (this.type === '1') {
          //   this.imagesurlarr.push(res.data.payload)
          //   this.$emit('ReturnImgUrl', this.imagesurl, this.key)
          // } else {
          this.imagesurlstr = res.data.payload;
          this.$emit(
            'ReturnImgUrl',
            this.imagesurlstr,
            this.key,
            dataA.file.name
          );
          // this.fileName = dataA.file.name;
          this.isPdf = dataA.file.name.replace(/.+\./, '').toLowerCase();
          this.$message({
            type: 'success',
            message: '上传成功',
            duration: 2000
          });
          this.loading = false;

          // }
        })
        .catch(() => {
          this.$message({
            type: 'error',
            message: '上传失败，请重新上传',
            duration: 2000
          });
          this.loading = false;
        });
    }
  }
};
</script>

<style lang="less">
.tableUpload-box {
  padding: 0;
  .view {
    display: flex;
    align-items: center;
    background-color: #fff;
    border: 1px solid #e8e8e8;
    width: 100%;
    height: 34px;
    padding: 0 5px;
    &:hover {
      cursor: pointer;
    }
    .el-image {
      width: 23px;
      height: 23px;
    }
    span {
      width: 100%;
      margin-left: 5px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
    // img {
    //   cursor: pointer;
    // }
  }
}
// .el-image-viewer__btn .el-image-viewer__close
.el-icon-circle-close {
  color: #fff;
  position: fixed;
  top: 0;
  right: 0;
}
.el-message-box__wrapper {
  z-index: 3000 !important;
}
</style>
